package com.tm.nettystudy.fixedLengthFrame;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;

public class NettyServerHandler extends ChannelInboundHandlerAdapter {
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {

        System.out.println ("channelActive打印" + Thread.currentThread ().getName () + ctx.channel ().remoteAddress ());
        //如果此handler后续还有handler的话,只有调用了fireXXX才能向下继续调用
        ctx.fireChannelActive ();
    }

    /**
     * 读取客户端发送的数据
     *
     * @param ctx 上下文对象, 含有通道channel，管道pipeline
     * @param msg 就是客户端发送的数据
     * @throws Exception
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
         //使用了Stingdecoder所以这里接受到消息就是string类型的,不需要再次抓交换
         System.out.println ("客户端发送消息是:" +msg);
        //这是返回给客户端消息,如果使用StringEncoder,直接发String类型就可以,如果没有使用就先转为ByteBuf
        ByteBuf buf1 = Unpooled.copiedBuffer ("HelloClient$_$", CharsetUtil.UTF_8);
        Channel channel = ctx.channel ();
        channel.writeAndFlush (buf1);
    }

    /**
     * 数据读取完毕处理方法,这个方法个人认为不太好用,
     *
     * @Override public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
     * System.out.println ("服务端接受消息结束");
     * ByteBuf buf = Unpooled.copiedBuffer ("HelloClient$_$", CharsetUtil.UTF_8);
     * ctx.writeAndFlush (buf);
     * }
     */
    @Override
    //处理异常, 一般是需要关闭通道
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.out.println (cause.getMessage ());
        ctx.close ();
    }
}